<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" >
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">
        <link rel="stylesheet" type="text/css" th:href="@{/css/bootstrap-clearmin.min.css}">
        <link rel="stylesheet" type="text/css" th:href="@{/css/roboto.css}">
        <link rel="stylesheet" type="text/css" th:href="@{/css/material-design.css}">
        <link rel="stylesheet" type="text/css" th:href="@{/css/small-n-flat.css}">
        <link rel="stylesheet" type="text/css" th:href="@{/css/font-awesome.min.css}">
        <link rel="stylesheet" type="text/css" th:href="@{/css/jquery-ui.min.css}">
        <link rel="stylesheet" type="text/css" th:href="@{/css/jquery-ui-timepicker-addon.min.css}">
        <title>Clearmin template</title>
    </head>
    <body class="cm-no-transition cm-2-navbar">
        <!-- 菜单 -->
        <div th:replace="common/menu :: menu"></div>
        <header th:replace="common/header :: header"></header>
        <div id="global">
            <style>.demo hr{margin:30px 0}</style>
            <div class="container-fluid">
                <div class="panel panel-default demo">
                    <div class="panel-body">
                        <h4>监控数据</h4>
                        <ul id="myTab" class="nav nav-tabs" role="tablist">
                            <li role="presentation" class="active"><a href="#propertyDiv" id="home-tab" role="tab" data-toggle="tab" aria-controls="home" aria-expanded="true">属性&服务</a></li>
                            <li role="presentation" class=""><a href="#eventDiv" role="tab" id="profile-tab" data-toggle="tab" aria-controls="profile" aria-expanded="false">事件</a></li>
                        </ul>
                        <br>
                        <div id="myTabContent" class="tab-content">
                            <div role="tabpanel" class="tab-pane fade active in" id="propertyDiv" aria-labelledby="home-tab">
                                <h4>属性</h4>
                                <div class="row cm-fix-height" id="propertyList">
                                    <div class="col-sm-3" th:each="property:${productAbilities['PROPERTY']}">
                                        <div class="panel panel-default" th:id="${property.value.funId}">
                                            <div class="panel-heading" th:text="${property.value.funName}"></div>
                                            <div class="panel-body" style="text-align: center;">
                                                <h3>
                                                    &nbsp;
                                                </h3>
                                                <br>
                                                <span class="date">&nbsp;</span>
                                            </div>
                                            <div class="panel-footer text-center">
                                                <a name="" class="btn btn-primary btn-xs">查看数据</a>
                                                <a name="update" class="btn btn-primary btn-xs">修改</a>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <hr>
                                <h4>服务</h4>
                                <div class="row cm-fix-height" id="serviceList">
                                    <div class="col-sm-3" th:each="service:${productAbilities['SERVICE']}">
                                        <div class="panel panel-default" th:id="${service.value.funId}">
                                            <div class="panel-heading" th:text="${service.value.funName}"></div>
                                            <div class="panel-body" style="text-align: center;">
                                                <div>
                                                    <span>描述：</span><span th:text="${service.value.fundes}"></span>
                                                </div>
                                                <div>
                                                    <span>调用方式：</span><span th:text="${service.value.callType}"></span>
                                                </div>
                                            </div>
                                            <div class="panel-footer text-center">
                                                <a name="update" class="btn btn-primary btn-xs">调用</a>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div role="tabpanel" class="tab-pane fade" id="eventDiv" aria-labelledby="profile-tab">
                                <h4>事件</h4>
                                <div class="row cm-fix-height" id="eventList">
                                    <div class="col-sm-3" th:each="event:${productAbilities['EVENT']}">
                                        <div class="panel panel-default" th:id="${event.value.funId}">
                                            <div class="panel-heading" th:text="${event.value.funName}"></div>
                                            <div class="panel-body" style="text-align: center;">
                                                <div id="eventContent" style="height: 70px;">

                                                </div>
                                                <br>
                                                <span class="date">&nbsp;</span>
                                            </div>
                                            <div class="panel-footer text-center">
                                                <button type="button" class="btn btn-info btn-xs" th:onclick="'javascript:eventRecords(\'' + ${event.value.funId} + '\');'" th:if="${event.value.eventType == 'INFO_EVENT_TYPE'}">信息</button>
                                                <button type="button" class="btn btn-primary btn-xs" th:onclick="'javascript:eventRecords(\'' + ${event.value.funId} + '\');'" th:if="${event.value.eventType == 'ALERT_EVENT_TYPE'}">告警</button>
                                                <button type="button" class="btn btn-danger btn-xs" th:onclick="'javascript:eventRecords(\'' + ${event.value.funId} + '\');'" th:if="${event.value.eventType == 'ERROR_EVENT_TYPE'}">故障</button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div id="propertySetDialog" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                            <h4 class="modal-title" id="myModalLabel">
                                属性信息
                                <a class="anchorjs-link" href="#myModalLabel"><span class="anchorjs-icon"></span></a>
                            </h4>
                        </div>
                        <div class="modal-body">
                            <form class="form-horizontal">
                                <input type="hidden" id="propertyId">
                                <div class="form-group">
                                    <label for="propertyName" class="col-sm-2 control-label">属性名称</label>
                                    <div class="col-sm-10">
                                        <input type="text" class="form-control" id="propertyName">
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label for="propertyValue" class="col-sm-2 control-label">属性值</label>
                                    <div class="col-sm-10">
                                        <input type="text" class="form-control" id="propertyValue">
                                    </div>
                                </div>
                            </form>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                            <button type="button" id="confirmEdit" class="btn btn-primary">确定</button>
                        </div>
                    </div>
                    <!-- /.modal-content -->
                </div>
                <!-- /.modal-dialog -->
            </div>
            <div id="serviceInvokeDialog" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                            <h4 class="modal-title">
                                服务信息
                                <a class="anchorjs-link" href="#myModalLabel"><span class="anchorjs-icon"></span></a>
                            </h4>
                        </div>
                        <div class="modal-body">
                            <form class="form-horizontal">
                                <input type="hidden" id="serviceId">
                                <div class="form-group">
                                    <label for="propertyName" class="col-sm-2 control-label">服务名称</label>
                                    <div class="col-sm-10">
                                        <input type="text" class="form-control" id="serviceName">
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label for="propertyValue" class="col-sm-2 control-label">参数</label>
                                    <div class="col-sm-10">
                                        <input type="text" class="form-control" id="serviceParams">
                                    </div>
                                </div>
                            </form>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                            <button type="button" id="serviceInvoke" class="btn btn-primary">确定</button>
                        </div>
                    </div>
                    <!-- /.modal-content -->
                </div>
                <!-- /.modal-dialog -->
            </div>
            <div th:replace="device/eventRecordsDialog :: eventRecordsDialog"></div>
            <footer th:replace="common/footer :: footer"></footer>
        </div>
        <script th:src="@{/js/lib/jquery-2.1.3.min.js}"></script>
        <script th:src="@{/js/jquery.mousewheel.min.js}"></script>
        <script th:src="@{/js/jquery.cookie.min.js}"></script>
        <script th:src="@{/js/fastclick.min.js}"></script>
        <script th:src="@{/js/bootstrap.min.js}"></script>
        <script th:src="@{/js/clearmin.min.js}"></script>
        <script th:src="@{/js/jquery-ui.min.js}"></script>
        <script th:src="@{/js/jquery-ui-timepicker-addon.min.js}"></script>
        <script th:src="@{/js/jquery-ui-timepicker-zh-CN.js}"></script>

        <!-- ajax轮询 -->
        <script th:inline="javascript">
            // 日期格式化
            Date.prototype.Format = function (fmt) { //author: meizz
                var o = {
                    "M+": this.getMonth() + 1, //月份
                    "d+": this.getDate(), //日
                    "H+": this.getHours(), //小时
                    "m+": this.getMinutes(), //分
                    "s+": this.getSeconds(), //秒
                    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
                    "S": this.getMilliseconds() //毫秒
                };
                if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
                for (var k in o)
                    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                return fmt;
            };

            $('#start').datetimepicker({
                showSecond: true,
                dateFormat: 'yy-mm-dd',
                timeFormat: 'hh:mm:ss'
            });

            $('#end').datetimepicker({
                showSecond: true,
                dateFormat: 'yy-mm-dd',
                timeFormat: 'hh:mm:ss'
            });

            var productAbility = $.parseJSON([[${productAbilitiesJson}]]);
            //console.log(productAbility);

            var productKey = [[${productKey}]];
            var deviceName = [[${deviceName}]];
            //console.log('productKey = ' + productKey + ', deviceName = ' + deviceName);

            var propertyNames = [];

            // 定时刷新属性
            var proprtyRefresh = setInterval(getProperty, 5000);
            //getProperty();

            // 定时刷新事件
            var proprtyRefresh = setInterval(getEvent, 8000);

            // 确认修改
            $("#propertySetDialog #confirmEdit").click(function () {
                var propertyId = $("#propertySetDialog #propertyId").val();
                var propertyValue = $("#propertySetDialog #propertyValue").val();

                $.ajax({
                    type: "POST",
                    url: "/device/data/property/set",
                    data: {
                        "deviceName": deviceName,
                        "productKey": productKey,
                        "propertiesJson": propertyValue
                    },
                    success: function(data){
                        //console.log(data);
                        if (!data) {
                            alert("修改失败");
                        }
                        $('#propertySetDialog').modal('hide');
                    }
                });
            });

            // 属性设置
            $("#propertyList .panel").each(function () {
                var panel = $(this);
                var propertyId = panel.attr("id");
                //console.log('propertyId: ' + propertyId);
                $(panel).find(".panel-footer a[name='update']").click(function () {
                    var propertyMetaDatas = productAbility['PROPERTY'];
                    var propertyMetaData = propertyMetaDatas[propertyId];

                    var propertyName = propertyMetaData['funName'];
                    $('#propertySetDialog #propertyName').val(propertyName);

                    var propertyValue = '{' + '"' + propertyId + '": }';
                    $('#propertySetDialog #propertyValue').val(propertyValue);
                    $('#propertySetDialog').modal();
                });
            });

            // 服务调用
            $("#serviceList .panel").each(function () {
                var panel = $(this);
                var serviceId = panel.attr("id");
                //console.log('propertyId: ' + propertyId);
                $(panel).find(".panel-footer a[name='update']").click(function () {
                    var serviceMetaDatas = productAbility['SERVICE'];
                    var serviceMetaData = serviceMetaDatas[serviceId];

                    var serviceName = serviceMetaData['funName'];
                    $('#serviceInvokeDialog #serviceName').val(serviceName);

                    $('#serviceInvokeDialog #serviceId').val(serviceId);
                    $('#serviceInvokeDialog').modal();
                });
            });

            // 确认调用
            $("#serviceInvokeDialog #serviceInvoke").click(function () {
                var serviceId = $("#serviceInvokeDialog #serviceId").val();
                var serviceParams = $("#serviceInvokeDialog #serviceParams").val();

                $.ajax({
                    type: "POST",
                    url: "/device/data/service/invoke",
                    data: {
                        "deviceName": deviceName,
                        "productKey": productKey,
                        "serviceName": serviceId,
                        "args": serviceParams
                    },
                    success: function(data){
                        //console.log(data);
                        if (!data) {
                            alert("调用失败");
                        }
                        $('#serviceInvokeDialog').modal('hide');
                    }
                });
            });

            /**
             * 获取上报事件
             */
            function getEvent() {
                $("#eventDiv .col-sm-3").find(".panel").each(function () {
                    var eventCode = $(this).attr('id');
                    //console.log(eventCode);
                    var eventUnit = $(this);
                    $.ajax({
                        type: "GET",
                        url: "/device/data/event/get",
                        data: {
                            "deviceName": deviceName,
                            "productKey": productKey,
                            "eventCode": eventCode
                        },
                        success: function(data){
                            //console.log(data);
                            var time = data['timestamp'];
                            eventUnit.find("span[class='date']").text(time);

                            var value = data['eventBody'];
                            if (value) {
                                eventUnit.find("#eventContent").html(JSON.stringify(value));
                            }
                        }
                    });
                });
            }

            /**
             * 获取上报属性
             */
            function getProperty() {
                if (propertyNames.length <= 0) {
                    $("#propertyList .panel").each(function () {
                        propertyNames.push($(this).attr("id"));
                    });
                }
                //console.log('propertyNames:' + propertyNames);
                $.ajax({
                    type: "get",
                    url: "/device/data/property/get",
                    data: {
                        "deviceName": deviceName,
                        "productKey": productKey,
                        "propertyNames": JSON.stringify(propertyNames)
                    },
                    success: function(data){
                        //console.log(data);
                        if (data.length > 0) {
                            var time = new Date().Format("yyyy-MM-dd HH:mm:ss");
                            //console.log(time);
                            for (var i in data) {
                                var pv = data[i];
                                var propertyId = pv.attribute;
                                var propertyValue = pv.value;

                                var propertyMetaDatas = productAbility['PROPERTY'];
                                var propertyMetaData = propertyMetaDatas[propertyId];
                                var dataType = propertyMetaData['dataType'];

                                // 当前属性dom结构
                                var propertyUnit = $("#" + propertyId);

                                if ("ARRAY" == dataType) {
                                    console.log('array:' + propertyValue);
                                } else if ("STRUCT" == dataType) {  // 结构体
                                    console.log(typeof propertyValue);
                                    var dataSpecsList = propertyMetaData['dataSpecsList'];
                                    //console.log(dataSpecsList);
                                    var fullContent = "";
                                    for(var key in propertyValue) {
                                        //console.log('key:' + key + ', value:' + propertyValue[key]);
                                        for (var j in dataSpecsList) {
                                            var identifier = dataSpecsList[j].identifier;
                                            if (key == identifier) {
                                                fullContent += dataSpecsList[j].childName + ': ' + propertyValue[key] + dataSpecsList[j].childSpecsDTO.unit;
                                                break;
                                            }
                                        }
                                    }

                                    var h3 = propertyUnit.find("h3");

                                    h3.text(fullContent);
                                } else if ("BOOL" == dataType || "ENUM" == dataType) {  // 布尔和枚举
                                    var dataSpecsList = propertyMetaData['dataSpecsList'];
                                    //console.log(dataSpecsList);
                                    var fullContent = "";
                                    for (var j in dataSpecsList) {
                                        var value = dataSpecsList[j].value;
                                        if (value == propertyValue) {
                                            fullContent = dataSpecsList[j].name;
                                            break;
                                        }
                                    }
                                    var h3 = propertyUnit.find("h3");

                                    h3.text(fullContent);
                                } else {    // 基本属性
                                    var dataSpec = propertyMetaData['dataSpecs'];
                                    var unitName = "";
                                    if (dataSpec) {
                                        unitName = dataSpec['unit'];
                                    }
                                    var fullContent = propertyValue + unitName;
                                    var h3 = propertyUnit.find("h3");
                                    if (fullContent.length > 11) {
                                        h3.attr("title", fullContent);
                                        h3.text(fullContent.substr(0, 8) + "...");
                                    } else {
                                        h3.text(fullContent);
                                    }
                                }
                                propertyUnit.find("span[class='date']").text(time);
                            }
                        }
                    }
                });
            }
            
            function eventRecords(eventCode) {
                $("#eventRecordsDialog #eventCode").val(eventCode);
                $('#eventRecordsDialog').modal();
            }
            
            function search2() {
                var eventCode = $("#eventRecordsDialog #eventCode").val();
                var eventType = $("#eventRecordsDialog #eventType").val();
                var start = $("#eventRecordsDialog #start").val();
                var end = $("#eventRecordsDialog #end").val();
                //console.log(eventCode);
                var eventUnit = $(this);
                $.ajax({
                    type: "GET",
                    url: "/device/data/event/list",
                    data: {
                        "deviceName": deviceName,
                        "productKey": productKey,
                        "eventCode": eventCode,
                        "eventType": eventType,
                        "start": start,
                        "end": end
                    },
                    success: function(data){
                        console.log(data);
                        if (data) {
                            var html = "";
                            for (var i in data) {
                                html += "<tr>"
                                var eventValue = data[i];
                                html += "<td>" + eventValue['eventName'] + "</td>";
                                html += "<td>" + eventValue['eventType'] + "</td>";
                                html += "<td>" + eventValue['timestamp'] + "</td>";
                                html += "<td>" + JSON.stringify(eventValue['eventBody']) + "</td>";
                                html += "</tr>";
                            }
                            $("#eventRecordsDialog table tbody").html(html);
                        }
                    }
                });
            }
        </script>
    </body>
</html>